package com.ca.project.Server.Modules.RotatingChat.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ca.project.COS.CosUtil;
import com.ca.project.Minio.Util.MinioUtil;
import com.ca.project.Server.Modules.RotatingChat.Context.UploadRotatingChatContext;
import com.ca.project.Server.Modules.RotatingChat.Converter.RotatingChatConverter;
import com.ca.project.Server.Modules.RotatingChat.Entity.Rotatingchat;
import com.ca.project.Server.Modules.RotatingChat.Service.RotatingChatService;
import com.ca.project.Server.Modules.RotatingChat.Mapper.RotatingchatMapper;
import com.ca.project.core.Exception.BusinessException;
import com.ca.project.core.Util.IdUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ASUS
 * @description 针对表【rotatingchat】的数据库操作Service实现
 * @createDate 2024-12-31 14:43:19
 */
@Service
public class RotatingchatServiceImpl extends ServiceImpl<RotatingchatMapper, Rotatingchat>
        implements RotatingChatService {

    @Autowired
    private RotatingChatConverter rotatingChatConverter;
    @Autowired
    private CosUtil cosUtil;

    @Autowired
    private MinioUtil minioUtil;

    /**
     * 上传轮播图
     *
     * @param uploadRotatingChatContext
     */
    @Transactional(rollbackFor = Exception.class)
    public void uploadRotatingChat(UploadRotatingChatContext uploadRotatingChatContext) {
        doUpload(uploadRotatingChatContext);
        doCreate(uploadRotatingChatContext);
    }

    /**
     * 禁用轮播图
     *
     * @param id
     */
    @Override
    public void disable(Long id) {
        LambdaUpdateWrapper<Rotatingchat> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Rotatingchat::getId, id)
                .set(Rotatingchat::getState, 0)
                .set(Rotatingchat::getUpdateTime, new Date());
        baseMapper.update(null, updateWrapper);
    }

    /**
     * 恢复轮播图
     *
     * @param id
     */
    @Override
    public void recover(Long id) {
        LambdaUpdateWrapper<Rotatingchat> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Rotatingchat::getId, id)
                .set(Rotatingchat::getState, 1)
                .set(Rotatingchat::getUpdateTime, new Date());
        baseMapper.update(null, updateWrapper);
    }

    /**
     * 分页
     *
     * @param currentPage
     * @param pageSize
     * @param rotatingchat
     * @return
     */
    @Override
    public IPage<Rotatingchat> getPage(Integer currentPage, Integer pageSize, Rotatingchat rotatingchat) {
        LambdaQueryWrapper<Rotatingchat> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(rotatingchat.getName())) {
            wrapper.like(Rotatingchat::getName, rotatingchat.getName());
        }
        IPage<Rotatingchat> page = new Page<>(currentPage, pageSize);
        baseMapper.selectPage(page, wrapper);
        return page;
    }

    /**
     * 分页
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public IPage<Rotatingchat> getPage(Integer currentPage, Integer pageSize) {
        IPage<Rotatingchat> page = new Page<>(currentPage, pageSize);
        baseMapper.selectPage(page, null);
        return page;
    }

    /**
     * 删除轮播图
     *
     * @param filename
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRotatingChat(String filename) {
        //cosUtil.deletePublicFile(filename);
        boolean success_1 = minioUtil.deleteFile(filename);
        if (!success_1)
            throw new BusinessException("服务器图片删除失败");
        QueryWrapper<Rotatingchat> wrapper = new QueryWrapper<>();
        wrapper.eq("r_key", filename);
        boolean success = baseMapper.delete(wrapper) > 0;
        if (!success)
            throw new BusinessException("轮播图删除失败");
        return success;
    }

    /****************************************************private***********************************************************/

    /**
     * 上传图片
     *
     * @param uploadRotatingChatContext
     */
    private void doUpload(UploadRotatingChatContext uploadRotatingChatContext) {
        Rotatingchat entity = rotatingChatConverter.UploadRotatingChatContext2Rotatingchat(uploadRotatingChatContext);

        MultipartFile file = uploadRotatingChatContext.getFile();
        if (file.isEmpty()) {
            throw new BusinessException("上传文件不能为空");
        }
        String filename = file.getOriginalFilename();
        if (filename != null && filename.contains(".")) {
            filename = filename.substring(0, filename.lastIndexOf(".")); // 获取文件名的前缀部分
        } else {
            throw new BusinessException("无效的文件名");
        }

        try {
            //String path = "/CA/";
            //HashMap map = cosUtil.uploadPublicFile(file, path);
            Map<String, Object> map = minioUtil.upload(file);

            //String key = (String) map.get("path");
            String url = (String) map.get("url");
            String key = (String) map.get("key");

            //if (key.startsWith("/")) {
            //    key = key.substring(1);
            //}

            final Long id = IdUtil.get();
            entity.setId(id);
            entity.setName(filename);
            entity.setRKey(key);
            entity.setUrl(url);
            entity.setUpdateTime(new Date());
            entity.setCreateTime(new Date());

            uploadRotatingChatContext.setEntity(entity);
        } catch (IOException e) {
            throw new BusinessException("文件上传到minio错误");
        }
    }

    /**
     * 创建轮播图实体
     *
     * @param uploadRotatingChatContext
     */
    private void doCreate(UploadRotatingChatContext uploadRotatingChatContext) {
        Rotatingchat entity = uploadRotatingChatContext.getEntity();

        if (entity == null)
            throw new BusinessException("轮播图实体不能为空");

        try {
            if (!save(entity))
                throw new BusinessException("轮播图创建失败");
        } catch (Exception e) {
            throw new BusinessException("轮播图创建失败,原因:" + e.getMessage());
        }
    }

}




